﻿using System;
using Me.Amon.Da.Db;
using Me.Amon.Da.Db.CRM;
using Me.Amon.Da.Db.POS;
using Me.Amon.M;
using Me.Amon.POS;
using Me.Amon.POS.C;
using Me.Amon.Util;

namespace Me.Amon.User
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            var user = WebUtil.CurrentUser(Session);
            if (user.Rank < IUser.LEVEL_01)
            {
                Response.Redirect(IEnv.HOME_PAGE);
                return;
            }

            LbCode.Text = user.Code;
            LbMail.Text = user.Mail;
            LbRank.Text = MUser.GetRankName(user.Rank);

            if (user.Code == IUser.ROOT_CODE)
            {
                HlSignUp.Text = "添加新用户";
                HlSignUp.NavigateUrl = "~/User/SignUp.aspx";
                HlSignUp.ToolTip = "添加新用户";
            }
            else
            {
                HlSignUp.Text = "下载客户端";
                HlSignUp.NavigateUrl = "/down/EasyPOS.exe";
                HlSignUp.ToolTip = "点击下载理店宝收银客户端";
            }

            HlKpt.Visible = user.Code == "A0000050";

            var dba = new RDBEngine();
            ReadCorp(dba, user.Code);
            dba.Reset();
            ReadTerminal(dba, user.Code);
        }

        private void ReadCorp(RDBEngine dba, string corp)
        {
            dba.AddTable(DCompany.TABLE);
            dba.AddWhere(DCompany.CODE, corp);
            dba.AddWhere(DCompany.STATUS, CPos.STATUE_ENABLED.ToString());

            var dt = dba.ExecuteSelect();
            if (dt.Rows.Count < 1)
            {
                return;
            }

            var row = dt.Rows[0];

            //LlCorpCode.Text = row[DCompany.CODE] as string;
            LlCorpName.Text = row[DCompany.NAME] as string;
            LlCorpAddress.Text = row[DCompany.ADDRESS] as string;
            LlCorpPostcode.Text = row[DCompany.POSTCODE] as string;
            HlCorpHomepage.Text = row[DCompany.HOMEPAGE] as string;
            HlCorpHomepage.NavigateUrl = HlCorpHomepage.Text;
            LlCorpContact.Text = row[DCompany.CONTACT] as string;
            LlCorpTelephone.Text = row[DCompany.TELEPHONE] as string;
        }

        private void ReadTerminal(RDBEngine dba, string corp)
        {
            var sql = string.Format(@"SELECT
  a.code       shopcode,
  a.name       shopname,
  a.address    shopaddr,
  b.code       poscode,
  b.name       posname,
  b.addr       posaddr
FROM pos_shop a,
  pos_terminal b
WHERE a.code = b.shop_id
    AND a.status = 1
    AND b.status = 1
    AND a.corp_id = '{0}'
    AND b.corp_id = '{0}'", corp);

            RpSpus.DataSource = dba.ExecuteSelect(sql);
            RpSpus.DataBind();
        }
    }
}